package com.kaoqin.code.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.kaoqin.code.util.AuthorUtils;
import com.kaoqin.model.SysLog;
import com.kaoqin.service.SysLogService;
import com.kaoqin.service.UserService;

/**
 * IP认证的拦截器
 */
public class IpInterceptor implements HandlerInterceptor {
	private UserService userService;
	private SysLogService sysLogService;
	
	public SysLogService getSysLogService() {
		return sysLogService;
	}
	public void setSysLogService(SysLogService sysLogService) {
		this.sysLogService = sysLogService;
	}
	/**
	 * @return the userService
	 */
	public UserService getUserService() {
		return userService;
	}
	/**
	 * @param userService the userService to set
	 */
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	/**
	 * Handler执行之前调用这个方法
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String ip = AuthorUtils.getIpAddr(request);
		String allowIp = userService.findIpAddress();
		if (StringUtils.isNotBlank(allowIp) && StringUtils.isNotBlank(ip)) {
			String[] allowIpArr = allowIp.split(",");
			boolean isOk = false;
			for (String ipStr : allowIpArr) {
				if (ipStr.equals(ip)) {
					isOk = true;
					request.setAttribute("currentIp", ip);
					break;
				}
			}
			if (isOk) {
				return true;
			}
		}
		getSysLog(request.getRequestURI(), ip, 1, null);
		//不符合条件的，跳转到登录界面  
		request.setAttribute("msg", "操作无效，请联系管理员!");
		request.getRequestDispatcher("/WEB-INF/jsp/error/404.jsp").forward(request, response);
		return false;
	}
	private void getSysLog(String requestURI, String ip, int isF,Integer userid) {
		SysLog logO=new SysLog();
		logO.setOpFunctionUrl(requestURI);
		logO.setOpIp(ip);
		logO.setOpIllegal(isF);
		logO.setOpDate(new Date());
		logO.setOpType("ip");
		sysLogService.insertOne(logO);
	}
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
	}
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
	}
}
